﻿using System;
using System.Linq;
using cludg.Domain.Content.Stories;
using cludg.Domain.Content.Stories.Subjects;
using cludg.Domain.Users;
using cludg.Repository.Content;
using cludg.Repository.Transactions;
using cludg.Services.Images;

namespace cludg.Services.Content
{

	public class OfferService : IOfferService
	{
		protected readonly IContentRepository<Offer> Repository;
		protected readonly IImageService ImageService;
		protected readonly IStoryService StoryService;
		protected readonly ITransactionFactory TransactionFactory;

		public OfferService(
			IContentRepository<Offer> repository, 
			ITransactionFactory transactionFactory,
			IStoryService storyService,
			IImageService imageService)
		{
			Repository = repository;
			TransactionFactory = transactionFactory;
			StoryService = storyService;
			ImageService = imageService;
		}

		#region IOfferService Members

		public IQueryable<Offer> All
		{
			get { return Repository.Get(); }
		}

		public Offer ById(string offerId)
		{
			return Repository.ById(offerId);
		}

		public Offer NewOffer(StorySubject subject, User author, string comment, string title, string anonymouseAutorName)
		{
			var addingOffer = new Offer
				{
					Subject = subject,
					Author = author,
					Comment = comment,
					Title = title,
					AnonymouseAuthorName = anonymouseAutorName,
					CreationTime = DateTime.Now
				};
			using (var tx = TransactionFactory.BeginTransaction())
			{
				Repository.Add(addingOffer);

				tx.Commit();
			}
			return addingOffer;
		}

		public Story Approve(Offer offer, User author, string title, string body, string anonymouseAutorName, string tags)
		{
			Story story = null;
			using (var tran = TransactionFactory.BeginTransaction())
			{
				story = StoryService.NewStory(offer.Subject.Clone(), author, offer.Author, title, body, anonymouseAutorName,
					tags);
				offer.Approve(author, story, DateTime.Now);
				Repository.Save(offer);
				tran.Commit();
			}
			return story;
		}

		public void Decline(Offer offer, User author)
		{
			using (var tran = TransactionFactory.BeginTransaction())
			{
				offer.Decline(author, DateTime.Now);
				tran.Commit();
			}
			Repository.Save(offer);
		}

		public void Delete(string offerId)
		{
			using (var tran = TransactionFactory.BeginTransaction())
			{
				Repository.Delete(offerId);
				tran.Commit();
			}
		}

		#endregion
	}
}
